#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/4/28 9:51
# @File    : 1.py
# @Description : -i http://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn


# -*- coding: utf-8 -*-
"""
@Time : 2023/2/11 2:29
@Auth : Junjie Duan
@File : 1读取ui文件.py
"""

import win32gui
import time
import airtest
import poco
from PIL import Image
import matplotlib.pyplot as plt
from airtest.core.api import *
from airtest.core.android.adb import *
from airtest.core.android import Android
from poco.drivers.android.uiautomation import AndroidUiautomationPoco


# android_device = connect_device('android://127.0.0.1:62001/127.0.0.1:62001?cap_method=javacap&touch_method=adb')

# from pywinauto import application
# app = application.Application().start_('notepad.exe')
# app.Notepad.MenuSelect('File->Open')
# # app.[window title].[control name]...
# app.Open.Edit.SetText('filename.txt')
# app.Open.Open.Click()


def show(dev):
    temp = dev.snapshot()
    # Image.fromarray(temp).show()
    plt.imshow(temp)
    plt.show()


def get_handle():
    hwnd_title = {}

    def get_all_hwnd(hwnd, mouse):
        if (win32gui.IsWindow(hwnd)
                and win32gui.IsWindowEnabled(hwnd)
                and win32gui.IsWindowVisible(hwnd)):
            hwnd_title.update({win32gui.GetWindowText(hwnd): hwnd})

    win32gui.EnumWindows(get_all_hwnd, 0)
    return hwnd_title


def get_device(path='Android://127.0.0.1:5037/127.0.0.1:62001?cap_method=JAVACAP'):
    android_device = connect_device(path)
    return android_device


def get_window(handele):
    """ 空表示全部句柄 """
    # connect_device("Windows:///?title_re=confirm.*")  # 正则
    return connect_device(f"Windows:///{handele}")


def doc():
    return """

    # touch((216, 741)) # 点开游戏

    # time.sleep(30)
    # touch((800, 713))  # 进入游戏

    touch((45, 160))  # 点击图鉴
    time.sleep(0.5)
    touch((590, 1700))  # 退出
    """


def input_file_to_nox():
    """
        导入安装包
    """
    handles = get_handle()
    print(handles)
    handle = handles.get('模拟器助手')

    if not handle:
        exit()

    dev_win = get_window(handle)
    # show(dev_win)
    touch((600, 560))  # 点击导入

    handles2 = get_handle()
    # print(handles2)
    handle2 = handles2.get('导入数据')
    dev_win2 = get_window(handle2)

    time.sleep(0.5)
    touch((670, 60))  # 点击路径选项
    dev_win2.text(r"C:\Users\86176\Desktop\duokai")
    time.sleep(1)
    touch((700, 60))  # 跳转路径选项
    touch((700, 60))  # 跳转路径选项
    time.sleep(1)
    touch(Template('1.png'))  # 选择文件 大象+游戏.npbk
    # dev_win2.key_release('ENTER')
    touch((790, 500))  # 跳转路径选项
    time.sleep(1)
    dev_win_all = get_window("")
    # show(dev_win_all)
    time.sleep(2)
    touch(Template('2.png'))  # 导入确认


def open_phone():
    """ 批量启动模拟器 """
    handles = get_handle()
    # print(handles)
    handle = handles.get('模拟器助手')

    if not handle:
        exit()

    dev_win = get_window(handle)

    touch((110, 90))  # 全选
    time.sleep(0.5)
    touch((130, 50))  # 开启

    # show(dev_win)


def close_phone():
    """ 批量启动模拟器 """
    handles = get_handle()
    # print(handles)
    handle = handles.get('模拟器助手')

    if not handle:
        exit()

    dev_win = get_window(handle)

    # touch((110, 90)) # 自动开启的不需要 全选
    time.sleep(0.5)
    # show(dev_win)

    touch((190, 50))  # 关闭

    dev_win = get_window("")
    # show(dev_win)
    if not is_exists(Template(r"3.png")):
        print("确认框不存在", )

    touch(Template("2.png"))

    # show(dev_win)


def get_device_all():
    """

    """
    adb = ADB()
    print(adb.devices())


def is_exists(v):
    try:
        assert_exists(v, "是确认关闭框！")
    except Exception as e:
        return False
    return True


def register():
    """"""
    path = 'Android://127.0.0.1:5037/127.0.0.1:62001?cap_method=JAVACAP'

    def step1():
        """ 安装magisk """
        dev = get_device(path)
        # android = Android("127.0.0.1:62026")
        poco = AndroidUiautomationPoco(dev)
        """"""
        print(poco(textMatches="途游.*").get_text())
        print(poco(textMatches="Magisk.*").get_text())
        poco(textMatches="Magisk.*Delta").click()
        time.sleep(.5)

        dev.touch((480, 120))  # 安装
        time.sleep(.5)
        dev.touch((480, 120))  # 下一步
        time.sleep(.5)
        # show(dev)
        dev.touch((130, 280))  # 安装系统分区
        time.sleep(.5)
        # show(dev)
        print("点击 ")
        dev.touch((470, 170))  # 开始安装
        time.sleep(.5)
        if is_exists(Template("8.png")):
            touch(Template("8.png"))  # 重启app
        # print(poco("io.github.huskydg.magisk:id/home_magisk_button"))

    try:
        step1()
        """  """
    except Exception as e:
        """ 重启手机错误检查 """
        print(" zZZ")

    time.sleep(30)

    def step2():
        """ lsp 检测 """

        dev = get_device(path)
        # show(dev)
        # stop_app('io.github.huskydg.magisk') # 关闭app

        """"""
        dev.keyevent('home')

        poco2 = AndroidUiautomationPoco(dev)

        poco2(textMatches="LSP.*").click()
        time.sleep(.5)

        dev.touch((145, 920))  # 点击lsp插件

        time.sleep(1)
        # show(dev)
        if is_exists(Template('4.png')):
            touch(Template('4.png'))
            print("点4.png")
        else:
            dev.touch((100, 180))  # 超级大象

        time.sleep(.5)
        if not is_exists(Template('5.png', threshold=0.95)):  # 检查是否勾选 途游 精度98
            raise RuntimeError('未勾选途游!')
        time.sleep(2)
        dev.keyevent('home')  # 返回主界面

    step2()

    def login():

        dev = get_device(path)
        poco3 = AndroidUiautomationPoco(dev)
        poco3(textMatches="超级大象.*").click()
        time.sleep(.5)
        touch((65, 150))
        dev.text("")
        time.sleep(1)
        touch((65, 200))
        dev.text("")
        time.sleep(1)

        touch((65, 150))
        dev.text("CGwARbTF")
        time.sleep(.5)
        touch((65, 200))
        dev.text("aa010203")
        time.sleep(.5)
        # show(dev)

        touch((270, 385))  # 登录超级大象
        touch((270, 385))  # 登录超级大象
        time.sleep(5)

        dev.keyevent('home')

        poco3(textMatches="途游.*").click()
        time.sleep(10)
        if is_exists(Template('6.png')):  # app安全协议
            print("安全协议1")
            touch(Template('6.png'))

        if is_exists(Template('7.png')):  # app安全协议
            print("安全协议2")
            touch(Template('7.png'))

        time.sleep(1)

        if is_exists(Template('9.png')):  # 允许拨打电话
            print("允许拨打电话")
            touch(Template('9.png'))
        print(" = 加载。。。 =")
        time.sleep(60 * 3)

        temp_flag_i = 0
        while True:
            if is_exists(Template('10.png')) or temp_flag_i >= 5:
                break
            elif is_exists(Template('13.png')):
                touch(Template('14.png'))  # 网络链接失败尝试
            else:
                time.sleep(3)
                temp_flag_i += 1

        time.sleep(.5)

        """

        # 登录大象！
        touch((65, 150))
        dev.text("CGwARbTF")
        time.sleep(.5)
        touch((65, 200))
        dev.text("aa010203")
        time.sleep(.5)

        #show(dev)
        touch((270, 285)) # 登录超级大象
        touch((270, 285)) # 登录超级大象

        """

        time.sleep(2)
        touch(Template('11.png'))  # 勾选协议
        time.sleep(5)
        touch(Template('12.png'))
        time.sleep(10)

        touch((270, 930))  # 授权
        time.sleep(10)
        # show(dev)

    login()

    dev = get_device(path)
    touch((300, 240))  # send id name
    dev.text("")
    time.sleep(.5)
    touch((300, 300))
    dev.text("")  # sen id num
    time.sleep(.5)
    touch((300, 240))  # send id name
    dev.text("张三")
    time.sleep(.5)
    touch((300, 300))
    dev.text("12345")  # sen id num
    time.sleep(1)
    touch((480, 360))
    show(dev)


if __name__ == '__main__':
    def login_dx():
        path = 'Android://127.0.0.1:5037/127.0.0.1:62001?cap_method=JAVACAP'
        dev = get_device(path)
        poco3 = AndroidUiautomationPoco(dev)
        poco3(textMatches="超级大象.*").click()
        time.sleep(1)
        touch((65, 150))
        dev.text("")
        time.sleep(1)
        touch((65, 200))
        dev.text("")
        time.sleep(1)

        touch((65, 150))
        dev.text("CGwARbTF")
        time.sleep(.5)
        touch((65, 200))
        dev.text("aa010203")
        time.sleep(.5)
        show(dev)

        touch((270, 385))  # 登录超级大象
        touch((270, 385))  # 登录超级大象

        time.sleep(5)
        print('cv 点击')
        touch(Template('15.png'))

        show(dev)

        exit()


    # login_dx()

    # 导入文件
    print("导入手机环境")
    input_file_to_nox()

    print("打开手机")
    open_phone()

    #
    # # 观察一下看看需要多久能打开
    time.sleep(50)
    print(get_device_all())
    time.sleep(5)
    # close_phone()

    # get_device_all()
    register()

    time.sleep(5)
    print("关闭所有手机！")
    close_phone()




